﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web.UI;
using Eneta.Portal.Common;
using Eneta.Portal.Common.Dto;
using Eneta.Portal.Common.Helpers;
using Eneta.Portal.Common.Repository;

namespace Eneta.Portal.Forum.Controls
{
    public partial class ForumsFrontPageControl : UserControl
    {
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            var forums = GetForums();

            _firstForumContainer.Visible = (forums[0] != null);
            if (forums[0] == null)
            {
                Logger.LogInfo("ForumsFrontPageControl.OnLoad(): First forum is null");
            }
            if (_firstForumContainer.Visible)
            {
                var block = forums[0];
                _firstForumTitleLink.HRef = EnetaApplication.PortalForumPageUrl + "?control=ViewTopics&forum=" + block.Forum.Id;
                _firstForumTitleLink.InnerText = block.Forum.Title;

                var topic = block.Topics[0];
                if (topic == null)
                {
                    Logger.LogInfo("ForumsFrontPageControl.OnLoad(): First forum first topic is null");
                }
                if (topic != null)
                {
                    _firstLargeLink.InnerText = topic.Title;
                    _firstLargeLink.HRef = EnetaApplication.PortalForumPageUrl + "?control=ViewMessages&topic=" + topic.Id;

                    if (topic.PostCount < 1)
                    {
                        _firstLargeCommentsLink.Visible = false;
                    }
                    else
                    {
                        _firstLargeCommentsLink.HRef = _firstLargeLink.HRef;
                        _firstLargeCommentsLink.InnerHtml = "<span>(" + topic.PostCount + ")</span>";
                    }
                    var body = RegExHelper.RemoveHtmlTags(block.FirstPost.Body);
                    if (body == null)
                        body = string.Empty;

                    body = RegExHelper.CleanForumBody(body);
                    body = GetFormattedBody(body);

                    body = body.Replace("&nbsp;", " ");
                    if (body.Length > 255)
                    {
                        body = body.Substring(0, 252) + "...";
                    }
                    _firstLargeSummary.InnerHtml = body;
                    _firstLargeDateAndUser.InnerText = block.FirstPost.Created.ToString("dd.MM.yyyy HH:mm");
                    _firstLargeDateAndUser.InnerText += "  |  " + block.FirstPost.AuthorProfileName;
                }
                topic = block.Topics[1];
                if (topic != null)
                {
                    _firstSmallLink.InnerText = topic.Title;
                    _firstSmallLink.HRef = EnetaApplication.PortalForumPageUrl + "?control=ViewMessages&topic=" + topic.Id;

                    if (topic.PostCount < 1)
                    {
                        _firstSmallCommentsLink.Visible = false;
                    }
                    else
                    {
                        _firstSmallCommentsLink.HRef = _firstSmallLink.HRef;
                        _firstSmallCommentsLink.InnerHtml = "<span>(" + topic.PostCount + ")</span>";
                    }
                }
                else
                {
                    Logger.LogInfo("ForumsFrontPageControl.OnLoad(): block.Topics[1] is null");
                    _firstSmallContainer.Visible = false;
                }
                topic = block.Topics[2];
                if (topic != null)
                {
                    _firstLastContainer.Visible = (topic.PostCount > 0);
                    _firstLastLink.InnerText = topic.Title;
                    _firstLastLink.HRef = EnetaApplication.PortalForumPageUrl + "?control=ViewMessages&topic=" + topic.Id;

                    if (topic.PostCount < 1)
                    {
                        _firstLastCommentsLink.Visible = false;
                    }
                    else
                    {
                        _firstLastCommentsLink.HRef = _firstLastLink.HRef;
                        _firstLastCommentsLink.InnerHtml = "<span>(" + topic.PostCount + ")</span>";
                    }
                }
                else
                {
                    Logger.LogInfo("ForumsFrontPageControl.OnLoad(): block.Topics[2] is null");
                    _firstLastContainer.Visible = false;
                }
            }


            _secondForumContainer.Visible = (forums[1] != null);
            if (_secondForumContainer.Visible)
            {
                var block = forums[1];
                _secondForumTitleLink.HRef = EnetaApplication.PortalForumPageUrl + "?control=ViewTopics&forum=" + block.Forum.Id;
                _secondForumTitleLink.InnerText = block.Forum.Title;

                var topic = block.Topics[0];
                if (topic != null)
                {
                    _secondLargeLink.InnerText = topic.Title;
                    _secondLargeLink.HRef = EnetaApplication.PortalForumPageUrl + "?control=ViewMessages&topic=" + topic.Id;

                    if (topic.PostCount < 1)
                    {
                        _secondLargeCommentsLink.Visible = false;
                    }
                    else
                    {
                        _secondLargeCommentsLink.HRef = _secondLargeLink.HRef;
                        _secondLargeCommentsLink.InnerHtml = "<span>(" + topic.PostCount + ")</span>";
                    }
                    var body = RegExHelper.RemoveHtmlTags(block.FirstPost.Body);
                    if (body == null)
                        body = string.Empty;

                    body = RegExHelper.CleanForumBody(body);
                    body = GetFormattedBody(body);


                    body = body.Replace("&nbsp;", " ");
                    if (body.Length > 255)
                    {
                        body = body.Substring(0, 252) + "...";
                    }
                    _secondLargeSummary.InnerHtml = body;
                    _secondLargeDateAndUser.InnerText = block.FirstPost.Created.ToString("dd.MM.yyyy HH:mm");
                    _secondLargeDateAndUser.InnerText += "  |  " + block.FirstPost.AuthorProfileName;

                }
                topic = block.Topics[1];
                if (topic != null)
                {
                    _secondSmallLink.InnerText = topic.Title;
                    _secondSmallLink.HRef = EnetaApplication.PortalForumPageUrl + "?control=ViewMessages&topic=" + topic.Id;

                    if (topic.PostCount < 1)
                    {
                        _secondSmallCommentsLink.Visible = false;
                    }
                    else
                    {
                        _secondSmallCommentsLink.HRef = _secondSmallLink.HRef;
                        _secondSmallCommentsLink.InnerHtml = "<span>(" + topic.PostCount + ")</span>";
                    }
                }
                else
                    _secondSmallContainer.Visible = false;

                topic = block.Topics[2];
                if (topic != null)
                {
                    _secondLastContainer.Visible = (topic.PostCount > 0);
                    _secondLastLink.InnerText = topic.Title;
                    _secondLastLink.HRef = EnetaApplication.PortalForumPageUrl + "?control=ViewMessages&topic=" + topic.Id;

                    if (topic.PostCount < 1)
                    {
                        _secondLastCommentsLink.Visible = false;
                    }
                    else
                    {
                        _secondLastCommentsLink.HRef = _secondLastLink.HRef;
                        _secondLastCommentsLink.InnerHtml = "<span>(" + topic.PostCount + ")</span>";
                    }
                }
                else
                    _secondLastContainer.Visible = false;

                _secondLastContainer.Visible = !string.IsNullOrEmpty(_secondLastLink.InnerText);
            }

            _thirdForumContainer.Visible = (forums[2] != null);
            if (_thirdForumContainer.Visible)
            {
                var block = forums[2];
                _thirdForumTitleLink.HRef = EnetaApplication.PortalForumPageUrl + "?control=ViewTopics&forum=" + block.Forum.Id;
                _thirdForumTitleLink.InnerText = block.Forum.Title;

                var topic = block.Topics[0];
                if (topic != null)
                {
                    _thirdLargeLink.InnerText = topic.Title;
                    _thirdLargeLink.HRef = EnetaApplication.PortalForumPageUrl + "?control=ViewMessages&topic=" + topic.Id;

                    if (topic.PostCount < 1)
                    {
                        _thirdLargeCommentsLink.Visible = false;
                    }
                    else
                    {
                        _thirdLargeCommentsLink.HRef = _thirdLargeLink.HRef;
                        _thirdLargeCommentsLink.InnerHtml = "<span>(" + topic.PostCount + ")</span>";
                    }

                    var body = RegExHelper.RemoveHtmlTags(block.FirstPost.Body);
                    if (body == null)
                        body = string.Empty;
                    body = RegExHelper.CleanForumBody(body);
                    body = GetFormattedBody(body);

                    body = body.Replace("&nbsp;", " ");
                    if (body.Length > 255)
                    {
                        body = body.Substring(0, 252) + "...";
                    }
                    _thirdLargeSummary.InnerHtml = body;
                    _thirdLargeDateAndUser.InnerText = block.FirstPost.Created.ToString("dd.MM.yyyy HH:mm");
                    _thirdLargeDateAndUser.InnerText += "  |  " + block.FirstPost.AuthorProfileName;

                }
                topic = block.Topics[1];
                if (topic != null)
                {
                    //_thirdSmallContainer.Visible = (topic.PostCount > 0);
                    //if (_thirdSmallContainer.Visible)
                    //{
                    _thirdSmallLink.InnerText = topic.Title;
                    _thirdSmallLink.HRef = EnetaApplication.PortalForumPageUrl + "?control=ViewMessages&topic=" + topic.Id;

                    if (topic.PostCount < 1)
                    {
                        _thirdSmallCommentsLink.Visible = false;
                    }
                    else
                    {
                        _thirdSmallCommentsLink.HRef = _thirdSmallLink.HRef;
                        _thirdSmallCommentsLink.InnerHtml = "<span>(" + topic.PostCount + ")</span>";
                    }
                    //}
                }
                else
                    _thirdSmallContainer.Visible = false;

                topic = block.Topics[2];
                if (topic != null)
                {
                    _thirdLastLink.InnerText = topic.Title;
                    _thirdLastLink.HRef = EnetaApplication.PortalForumPageUrl + "?control=ViewMessages&topic=" + topic.Id;

                    if (topic.PostCount < 1)
                    {
                        _thirdLastCommentsLink.Visible = false;
                    }
                    else
                    {
                        _thirdLastCommentsLink.HRef = _thirdLastLink.HRef;
                        _thirdLastCommentsLink.InnerHtml = "<span>(" + topic.PostCount + ")</span>";
                    }
                }
                else
                    _thirdLastContainer.Visible = false;

                _thirdLastContainer.Visible = !string.IsNullOrEmpty(_thirdLastLink.InnerText);
            }
        }
        private IList<ForumBlock> GetForums()
        {
            var repository = new ForumRepository(EnetaApplication.PortalForumSiteUrl);
            var forums = repository.GetForumsForFrontPage();
            var blocks = new List<ForumBlock>();

            if (forums == null)
                forums = new List<ForumDto>();

            for (var i = 0; i < 3 - forums.Count; i++)
                forums.Add(null);

            for (var forumCounter = 0; forumCounter < Math.Min(3, forums.Count); forumCounter++)
            {
                var forum = forums[forumCounter];

                if (forum == null)
                {
                    blocks.Add(null);
                    continue;
                }

                var block = new ForumBlock();
                block.Forum = forum;
                block.Topics = repository.GetTopicsByForumId(forum.Id, 10);
                block.Topics = block.Topics.OrderByDescending(p => p.LastPostDate).ToList();
                block.Topics = block.Topics.Take(3).ToList();

                if (block.Topics.Count > 0)
                {
                    var posts = repository.GetForumPostsByTopicId(block.Topics[0].Id);
                    if (posts != null)
                        if (posts.Count > 0)
                            block.FirstPost = posts[posts.Count - 1];
                }

                for (var i = 0; i <= 3 - block.Topics.Count; i++)
                    block.Topics.Add(null);


                blocks.Add(block);
            }

            return blocks;
        }

        private static string GetFormattedBody(string body)
        {
            const string pattern = @"(\[quote\s+name=""(?<user>\w+)""\]|\[quote\])";

            var matches = Regex.Matches(body, pattern, RegexOptions.IgnoreCase | RegexOptions.Singleline);
            if (matches.Count == 0)
            {

                return body;
            }
            foreach (Match match in matches)
            {

                var user = string.Empty;
                if (match.Groups["user"] != null)
                    user = match.Groups["user"].Value;

                var replace = string.Empty;

                if (!string.IsNullOrEmpty(user))
                {
                    replace += user + " " + Resources.GetResourceString("UserWroteLabel") + " ";
                }
                body = body.Replace(match.ToString(), replace);
            }

            return body;
        }

        private class ForumBlock
        {
            public ForumBlock()
            {
                Topics = new List<ForumTopicDto>();
            }

            public ForumDto Forum { get; set; }
            public IList<ForumTopicDto> Topics { get; set; }
            public ForumPostDto FirstPost { get; set; }
        }

    }
}
